<template>
    <div class="timeline-container">
        <n-card class="timeline-card">
            <template #header>
                <div class="card-header">
                    <h1>时间轴编辑器</h1>
                    <div class="header-actions">
                        <n-button @click="saveTimeline" type="primary">
                            <template #icon><n-icon>
                                    <SaveOutline />
                                </n-icon></template>
                            保存时间轴
                        </n-button>
                        <n-button @click="goBack">
                            <template #icon>
                                <n-icon>
                                    <ArrowBackOutline />
                                </n-icon>
                            </template>
                            返回
                        </n-button>
                    </div>
                </div>
            </template>

            <div class="timeline-content">
                <div class="timeline-toolbar">
                    <n-button-group>
                        <n-button @click="play">
                            <template #icon><n-icon>
                                    <PlayOutline />
                                </n-icon></template>
                            播放
                        </n-button>
                        <n-button @click="pause">
                            <template #icon><n-icon>
                                    <PauseOutline />
                                </n-icon></template>
                            暂停
                        </n-button>
                        <n-button @click="stop">
                            <template #icon><n-icon>
                                    <StopOutline />
                                </n-icon></template>
                            停止
                        </n-button>
                    </n-button-group>

                    <n-space>
                        <n-input-number v-model:value="currentFrame" :min="0" :max="totalFrames" :step="1"
                            size="small" />
                        <span class="frame-info">/ {{ totalFrames }} 帧</span>
                    </n-space>

                    <n-select v-model:value="zoomLevel" :options="zoomOptions" size="small" style="width: 100px;" />
                </div>

                <div class="timeline-view">
                    <div class="tracks-container">
                        <!-- 轨道列表 -->
                        <div class="track-labels">
                            <div v-for="track in tracks" :key="track.id" class="track-label">
                                <div class="track-header">
                                    <n-checkbox v-model:checked="track.visible"></n-checkbox>
                                    <span class="track-name">{{ track.name }}</span>
                                </div>
                            </div>
                        </div>

                        <!-- 时间轴内容 -->
                        <div class="track-content" ref="trackContentRef">
                            <!-- 时间刻度 -->
                            <div class="time-ruler">
                                <div v-for="i in rulerMarks" :key="i" class="ruler-mark">
                                    <div class="mark-line"></div>
                                    <div class="mark-label">{{ formatTime(i) }}</div>
                                </div>
                            </div>

                            <!-- 轨道内容 -->
                            <div v-for="track in tracks" :key="track.id" class="track-timeline">
                                <div v-for="keyframe in track.keyframes" :key="keyframe.id" class="keyframe"
                                    :style="{ left: `${keyframe.time / totalDuration * 100}%` }"
                                    @click="selectKeyframe(keyframe)">
                                </div>
                            </div>

                            <!-- 当前时间指示器 -->
                            <div class="time-indicator" :style="{ left: `${currentTime / totalDuration * 100}%` }">
                            </div>
                        </div>
                    </div>
                </div>

                <div class="keyframe-editor" v-if="selectedKeyframe">
                    <h3>关键帧编辑</h3>
                    <n-form :model="keyframeForm" label-placement="left" label-width="100"
                        require-mark-placement="right-hanging">
                        <n-form-item label="时间" path="time">
                            <n-input-number v-model:value="keyframeForm.time" :min="0" :step="1" />
                        </n-form-item>

                        <n-form-item label="缓动函数" path="easing">
                            <n-select v-model:value="keyframeForm.easing" :options="easingOptions" />
                        </n-form-item>

                        <!-- 根据轨道类型显示不同的编辑器 -->
                        <template v-if="selectedTrack.type === 'character'">
                            <n-form-item label="姿势" path="pose">
                                <n-select v-model:value="keyframeForm.pose" :options="poseOptions" />
                            </n-form-item>
                        </template>

                        <template v-if="selectedTrack.type === 'camera'">
                            <n-form-item label="位置X" path="positionX">
                                <n-input-number v-model:value="keyframeForm.positionX" />
                            </n-form-item>
                            <n-form-item label="位置Y" path="positionY">
                                <n-input-number v-model:value="keyframeForm.positionY" />
                            </n-form-item>
                            <n-form-item label="缩放" path="scale">
                                <n-input-number v-model:value="keyframeForm.scale" :min="0.1" :step="0.1" />
                            </n-form-item>
                        </template>

                        <n-space justify="end">
                            <n-button @click="updateKeyframe" type="primary">更新</n-button>
                            <n-button @click="deleteKeyframe" type="error">删除</n-button>
                        </n-space>
                    </n-form>
                </div>
            </div>
        </n-card>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useMessage } from 'naive-ui'
import {
    NCard,
    NButton,
    NButtonGroup,
    NIcon,
    NSpace,
    NInputNumber,
    NSelect,
    NCheckbox,
    NForm,
    NFormItem
} from 'naive-ui'
import {
    SaveOutline,
    ArrowBackOutline,
    PlayOutline,
    PauseOutline,
    StopOutline
} from '@vicons/ionicons5'

const router = useRouter()
const message = useMessage()
const trackContentRef = ref(null)

// 时间轴数据
const currentTime = ref(0)
const currentFrame = ref(0)
const totalDuration = ref(60000) // 60秒
const totalFrames = ref(1800) // 60秒 × 30fps
const zoomLevel = ref(1)
const rulerMarks = ref(60) // 60个刻度

// 选中的关键帧
const selectedKeyframe = ref(null)
const selectedTrack = ref(null)

// 轨道数据
const tracks = ref([
    {
        id: 'track1',
        name: '角色 1',
        type: 'character',
        visible: true,
        locked: false,
        keyframes: [
            { id: 'kf1', time: 0, value: { pose: 'pose1' }, easing: 'linear' },
            { id: 'kf2', time: 15000, value: { pose: 'pose2' }, easing: 'ease-out' }
        ]
    },
    {
        id: 'track2',
        name: '相机',
        type: 'camera',
        visible: true,
        locked: false,
        keyframes: [
            { id: 'kf3', time: 0, value: { positionX: 0, positionY: 0, scale: 1 }, easing: 'linear' },
            { id: 'kf4', time: 30000, value: { positionX: 100, positionY: 50, scale: 1.5 }, easing: 'ease-in-out' }
        ]
    },
    {
        id: 'track3',
        name: '场景',
        type: 'scene',
        visible: true,
        locked: false,
        keyframes: [
            { id: 'kf5', time: 0, value: { scene: 'scene1' }, easing: 'linear' },
            { id: 'kf6', time: 45000, value: { scene: 'scene2' }, easing: 'linear' }
        ]
    }
])

// 关键帧表单
const keyframeForm = reactive({
    time: 0,
    easing: 'linear',
    pose: '',
    positionX: 0,
    positionY: 0,
    scale: 1
})

// 缓动函数选项
const easingOptions = [
    { label: '线性', value: 'linear' },
    { label: '渐入', value: 'ease-in' },
    { label: '渐出', value: 'ease-out' },
    { label: '渐入渐出', value: 'ease-in-out' }
]

// 姿势选项
const poseOptions = [
    { label: '站立', value: 'pose1' },
    { label: '行走', value: 'pose2' },
    { label: '跑步', value: 'pose3' },
    { label: '跳跃', value: 'pose4' }
]

// 缩放选项
const zoomOptions = [
    { label: '50%', value: 0.5 },
    { label: '100%', value: 1 },
    { label: '150%', value: 1.5 },
    { label: '200%', value: 2 }
]

// 格式化时间
const formatTime = (seconds: number) => {
    const totalSeconds = Math.floor(seconds)
    const minutes = Math.floor(totalSeconds / 60)
    const remainingSeconds = totalSeconds % 60
    return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
}

// 选择关键帧
const selectKeyframe = (keyframe: any) => {
    selectedKeyframe.value = keyframe
    selectedTrack.value = tracks.value.find(track =>
        track.keyframes.some(kf => kf.id === keyframe.id)
    )

    // 更新表单数据
    keyframeForm.time = keyframe.time
    keyframeForm.easing = keyframe.easing

    if (selectedTrack.value.type === 'character') {
        keyframeForm.pose = keyframe.value.pose
    } else if (selectedTrack.value.type === 'camera') {
        keyframeForm.positionX = keyframe.value.positionX
        keyframeForm.positionY = keyframe.value.positionY
        keyframeForm.scale = keyframe.value.scale
    }

    message.success(`已选择关键帧: ${keyframe.id}`)
}

// 更新关键帧
const updateKeyframe = () => {
    if (!selectedKeyframe.value) return

    // 更新关键帧数据
    selectedKeyframe.value.time = keyframeForm.time
    selectedKeyframe.value.easing = keyframeForm.easing

    if (selectedTrack.value.type === 'character') {
        selectedKeyframe.value.value.pose = keyframeForm.pose
    } else if (selectedTrack.value.type === 'camera') {
        selectedKeyframe.value.value.positionX = keyframeForm.positionX
        selectedKeyframe.value.value.positionY = keyframeForm.positionY
        selectedKeyframe.value.value.scale = keyframeForm.scale
    }

    message.success('关键帧已更新')
}

// 删除关键帧
const deleteKeyframe = () => {
    if (!selectedKeyframe.value) return

    // 从轨道中删除关键帧
    const track = tracks.value.find(track =>
        track.keyframes.some(kf => kf.id === selectedKeyframe.value.id)
    )

    if (track) {
        track.keyframes = track.keyframes.filter(kf => kf.id !== selectedKeyframe.value.id)
        selectedKeyframe.value = null
        message.success('关键帧已删除')
    }
}

// 播放控制
const play = () => {
    message.success('开始播放')
}

const pause = () => {
    message.success('已暂停')
}

const stop = () => {
    currentTime.value = 0
    currentFrame.value = 0
    message.success('已停止')
}

// 保存时间轴
const saveTimeline = () => {
    message.success('时间轴已保存')
}

// 返回上一页
const goBack = () => {
    router.back()
}

// 生命周期钩子
onMounted(() => {
    // 初始化
})
</script>

<style lang="scss" scoped>
.timeline-container {
    padding: 20px;
    height: 100%;
    overflow-y: auto;

    .timeline-card {
        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;

            h1 {
                margin: 0;
                font-size: 24px;
                font-weight: 500;
            }

            .header-actions {
                display: flex;
                gap: 12px;
            }
        }
    }

    .timeline-content {
        display: flex;
        flex-direction: column;
        gap: 16px;

        .timeline-toolbar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 8px 0;

            .frame-info {
                font-size: 14px;
                color: var(--text-color-secondary);
            }
        }

        .timeline-view {
            border: 1px solid var(--border-color);
            border-radius: 4px;
            overflow: hidden;
            height: 300px;

            .tracks-container {
                display: flex;
                height: 100%;

                .track-labels {
                    width: 150px;
                    border-right: 1px solid var(--border-color);
                    background-color: var(--card-color);

                    .track-label {
                        height: 40px;
                        border-bottom: 1px solid var(--border-color);
                        padding: 0 8px;

                        .track-header {
                            display: flex;
                            align-items: center;
                            height: 100%;
                            gap: 8px;

                            .track-name {
                                white-space: nowrap;
                                overflow: hidden;
                                text-overflow: ellipsis;
                            }
                        }
                    }
                }

                .track-content {
                    flex: 1;
                    position: relative;
                    overflow-x: auto;
                    background-color: var(--body-color);

                    .time-ruler {
                        height: 24px;
                        background-color: var(--card-color);
                        border-bottom: 1px solid var(--border-color);
                        position: relative;

                        .ruler-mark {
                            position: absolute;
                            height: 100%;

                            .mark-line {
                                height: 8px;
                                width: 1px;
                                background-color: var(--border-color);
                                position: absolute;
                                top: 16px;
                            }

                            .mark-label {
                                font-size: 10px;
                                color: var(--text-color-secondary);
                                position: absolute;
                                top: 0;
                                transform: translateX(-50%);
                            }
                        }
                    }

                    .track-timeline {
                        height: 40px;
                        border-bottom: 1px solid var(--border-color);
                        position: relative;

                        .keyframe {
                            position: absolute;
                            width: 10px;
                            height: 10px;
                            background-color: var(--primary-color);
                            border-radius: 50%;
                            top: 50%;
                            transform: translate(-50%, -50%);
                            cursor: pointer;

                            &:hover {
                                background-color: var(--primary-color-hover);
                                transform: translate(-50%, -50%) scale(1.2);
                            }
                        }
                    }

                    .time-indicator {
                        position: absolute;
                        top: 0;
                        bottom: 0;
                        width: 2px;
                        background-color: var(--error-color);
                        pointer-events: none;
                    }
                }
            }
        }

        .keyframe-editor {
            border: 1px solid var(--border-color);
            border-radius: 4px;
            padding: 16px;

            h3 {
                margin-top: 0;
                margin-bottom: 16px;
                font-size: 16px;
            }
        }
    }
}

/* 响应式调整 */
@media (max-width: 768px) {
    .timeline-container {
        padding: 10px;
    }
}
</style>